import time
import re
import datetime
import requests
import json


def getList(id):
    data = []
    with open('result.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        for line in lines:
            line = line = line.strip().split(",")
            if (id != "0" and line[2] == id):
                exist = existWareHouse(line[0])
                data.append({
                    'code': line[0],
                    'name': line[1],
                    'exist': exist
                })
            if id == "0":
                data.append({
                    'code': line[0],
                    'name': line[1],
                    'type': line[2]
                })
    return data


HEADERS = {
    "Origin": "https://xueqiu.com",
    "Referer": "https://xueqiu.com/S/SZ002372",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36",
    "cookie": "device_id=24700f9f1986800ab4fcc880530dd0ed; s=dp11eckvkd; cookiesu=221583286466240; Hm_lvt_1db88642e346389874251b5a1eded6e3=1582849941,1583115672,1583195966,1583286466; xq_a_token=66e8a3f551509aa69374d910934c68b74e4a3531; xqat=66e8a3f551509aa69374d910934c68b74e4a3531; xq_r_token=05bb35ff0d538ea379799710359c5135ed3d1ba9; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOjE4OTI5OTIwODcsImlzcyI6InVjIiwiZXhwIjoxNTg1ODc4NDg0LCJjdG0iOjE1ODMyODY0ODQ1MDIsImNpZCI6ImQ5ZDBuNEFadXAifQ.pEpvGMXK2dSM-bHADNOU_x9txymZFpEgv0xLZw9wu-fcmNicE16n-qKWfGS9SAtXw9XGVX5tbSHq6n7XqBeOZL86HON3_T44d1WcDCvzF6lWldMWs0aenhxA98z4bqpiWI_UcS4lIHbFYo3TBp-L4J6_zj7FSu3Px2KW2MRxOdOpHfqs2PGldMEfQELK_TZMSYdLjS9CC4VF84EpIPl1HQaBLcfXg98rAV7eSGKzm7gg9QgEYRyRcGh4W_P_crSDaGl37RNMzZOPooDZyWNqMjrLRFdncid9yQNX1VW7zcIIpa5igK9NcZQXwdwZBjSAg--19ZEPbq9X6DrETc1PvA; xq_is_login=1; u=1892992087; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1583286486"
}
format_time = datetime.datetime.now().strftime('%Y-%m-%d') + " 00:00:00"
ts = time.strptime(format_time, "%Y-%m-%d %H:%M:%S")
TIMESTAMP = int(time.mktime(ts) * 1000)


# ["0时间戳","1成交量","2开盘价","3最高价","4最低价","5收盘价","6涨跌额","7涨跌幅","8换手率","9成交额"]
def getSingleOnline(code, type, area):
    # session = requests.session()
    # post_url = 'https://xueqiu.com'
    # session.get(post_url, headers=HEADERS)

    ex = 'SH' if re.match('6[0-9]{5}', code) else 'SZ'
    URL = 'https://stock.xueqiu.com/v5/stock/chart/kline.json?symbol=%s%s&begin=%s&period=%s&type=before&count=%s' % (
        ex, code, TIMESTAMP, type, area)
    json_data = requests.get(url=URL, headers=HEADERS, allow_redirects=False).text
    _json = json.loads(json_data)
    writeArr = _json['data']['item']
    returnArr = []
    for item in writeArr:
        returnArr.append({
            'date': item[0],
            'cjl': item[1],
            'open': item[2],
            'high': item[3],
            'low': item[4],
            'close': item[5],
            'zdf': item[7],
            'hsl': item[8],
            'cje': item[9]
        })
    return returnArr


def switchDate(stamp):
    stamp = int(stamp) / 1000
    timeArray = time.localtime(stamp)
    otherStyleTime = time.strftime("%Y%m%d", timeArray)
    return otherStyleTime


# 添加到自选
def addWareHouse(code, name, price):
    fp = open('warehouse.txt', 'a', encoding='utf-8')
    fp.write('%s,%s,%s,%s\n' % (TIMESTAMP, code, name, price))
    fp.close()
    return True


def removeWareHouse(code):
    with open('warehouse.txt', 'r', encoding='utf-8') as r:
        lines = r.readlines()
    with open('warehouse.txt', 'w', encoding='utf-8') as w:
        for line in lines:
            c = line.split(',')[1]
            if c != code:
                w.write(line)
    return True

def existWareHouse(code):
    exist = False
    with open('warehouse.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        for line in lines:
            c = line.split(',')[1]
            if c == code:
                exist = True
                break
    return exist


if __name__ == '__main__':
    getSingleOnline('000030', 'day', '-150')
    # test()
